﻿using Camelot.JSONAPI.Business;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text.RegularExpressions;
using Command = Camelot.JSONAPI.Models.Command;

namespace Camelot.JSONAPI
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, IncludeExceptionDetailInFaults = true)]
    public class JsonService : IJsonService
    {
        [OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
        public string Items(string command)
        {
            // Test if array or not
            var isCommandArray = Regex.IsMatch(command.Trim(), @"^\[.*?\]$");
            string jsonReturn = string.Empty;

            if (isCommandArray)
            {
                List<Command> commandObj = JsonConvert.DeserializeObject<List<Command>>(command);

                List<string> ret = commandObj.Select(item => ExecuteFactory.Execute(item)).ToList();
                jsonReturn = string.Format("[{0}]", string.Join(",", ret.ToArray()));
            }
            else
            {
                Command commandObj = JsonConvert.DeserializeObject<Command>(command);
                jsonReturn = ExecuteFactory.Execute(commandObj);
            }

            return jsonReturn;
        }

        public string GetUser()
        {
            return OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name;
            //return WindowsIdentity.GetCurrent().Name; 
        }
    }
}
